<?php

namespace app\index\controller;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
use fast\Http;
use think\Hook;
use think\Cache;
use app\common\model\Trade as TradeModel;
use app\common\model\trade\Log as Tradelog;
use think\Db;
use app\common\library\Sms as Smslib;
use app\common\library\Ems as Emslib;

/**
 * 公共接口
 */
class Common extends Api
{

    protected $noNeedLogin = ['init','service','getQuotation','match','match2','coinmarketcap','coinmarketcap2','getinform','about','sysinfo'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        
        // Hook::add('upload_successed', function ($trade_id,$image) {
        //     $log = new Tradelog();
        //     $log->where('id',$trade_id)->update(['image'=>$image]);
        // });
    }

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');
            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => Config::get('upload'),
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     *
     * @param File $file 文件流
     */
    public function upload()
    {
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            $this->error(__('Uploaded file format is limited'));
        }
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'admin_id'    => 0,
                'user_id'     => (int)$this->auth->id,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            

            $this->success(__('Upload successful'), [
                'url' => $uploadDir . $splInfo->getSaveName()
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }


    /**
     * 客服接口
     * 
     */
    public function service()
    {
        $qq = config('site.basic_qq');
        $phone = config('site.basic_pohne');
        $this->success('返回成功',['qq'=>$qq,'phone'=>$phone]);
    }

    public function coinmarketcap()
    {
        $coinmarketcap = Http::sendRequest('https://api.coinmarketcap.com/v2/ticker/?convert=CNY&limit=2',[],'get');
        $coinmarketcapusdt = Http::sendRequest('https://api.coinmarketcap.com/v2/ticker/?start=8&limit=1&convert=CNY',[],'get');
        $icoinfo = json_decode($coinmarketcap['msg'],true);
        $icoinfouusdt = json_decode($coinmarketcapusdt['msg'],true);

        if ($icoinfo) {
            Cache::set('icoinfo',$icoinfo); 
            Cache::set('icoinfouusdt',$icoinfouusdt); 
        }
        $this->success('返回成功',['icoinfo'=>$icoinfo,'icoinfouusdt'=>$icoinfouusdt['data']['825']]);
    }
    

    public function getQuotation()
    {
        $icoinfo = Cache::get('icoinfo'); 
        $icoinfouusdt = Cache::get('icoinfouusdt'); 
        $syscoinyb =Db::name('coin')->where('symbol','USD')->find();
        $syscoinfae = Db::name('coin')->where('symbol','FAE')->find();
        $sysicoinfo = [
            'data'=>[
                'USD'=>[
                    'symbol'    =>  'USD',
                    'quotes'    =>  [
                        'CNY'   =>  ['price'=>floatval($icoinfouusdt['data']['825']['quotes']['CNY']['price']),'percent_change_1h'=>$icoinfouusdt['data']['825']['quotes']['CNY']['percent_change_1h']],
                        'USD'   =>  ['price'=>floatval($icoinfouusdt['data']['825']['quotes']['USD']['price']),'percent_change_1h'=>$icoinfouusdt['data']['825']['quotes']['CNY']['percent_change_1h']]
                    ]
                ],
                'FAE'=>[
                    'symbol'    =>  'FAE',
                    'quotes'    =>  [
                        'CNY'   =>  ['price'=>floatval($syscoinfae['exch_rate']),'percent_change_1h'=>0],
                        'USD'   =>  ['price'=>floatval($syscoinfae['exch_rate_usd']),'percent_change_1h'=>0]

                    ]
                ]
            ]
        ];
        $this->success('返回成功',['icoinfo'=>$icoinfo,'sysicoinfo'=>$sysicoinfo]);
    }

    //场内交易
    public function match()
    {
        // Cache::rm('running1'); 
        if (Cache::get('running1')) {
            $this->error('正在进行中');
        }
        Cache::set('running1',true);

        $tradeModel =new TradeModel();
        $trade =  $tradeModel->where('symbol','USD')->where('tosymbol','FAE')->where('surplusnum','>',0)->where('action','sell')->where('status','in',['0','1'])->find();
        if (!$trade) {
            Cache::rm('running1'); 
            $this->error('没有卖出订单');
        }

        $surplus = $trade->surplusnum;
        while ($surplus > 0) {
            $tradebuy =  $tradeModel->where('user_id','<>',$trade->user_id)->where('symbol','USD')->where('tosymbol','FAE')->where('action','buy')->where('surplusnum','>',0)->where('status','in',['0','1'])->find();
            if ($tradebuy) {
                $tradenum =  $surplus - $tradebuy->surplusnum > 0 ? $tradebuy->surplusnum : $surplus;
                $tradeno = Random::tradeno();
                Tradelog::Log($tradeno,$tradebuy->user_id,$tradebuy->user->username,$tradebuy->id,$trade->user_id,$trade->user->username,$trade->id,$tradenum,$tradenum,$trade->exch_rate,'waitting','admin',$trade['symbol'],$trade['tosymbol'],$trade['pay']);
                $tradeModel->dec('surplusnum',$tradenum)->where('id',$trade->id)->update(['status'=>'1']);
                $tradeModel->dec('surplusnum',$tradenum)->where('id',$tradebuy->id)->update(['status'=>'1']);
                $user_sell = Db::name('user')->where('id',$trade->user_id)->find();


                // if ($user_sell->mobile) {
                //      Smslib::smsNotice(['mobile'=>$user_sell->mobile,'']);
                // }
                
                // 您订单号为1111293094309，买入USD888个，订单已经匹配成功，请及时登录后台，查找卖方信息并及时转账。如您30分钟内没有转账系统将取消这笔订单。恶意操作，可能造成封号。
                $msg = "您订单号为{$tradeno}，买入{$trade['tosymbol']}{$tradenum}个，订单已经匹配成功，请及时登录后台，查找卖方信息并及时转账。如您30分钟内没有转账系统将取消这笔订单。恶意操作，可能造成封号。";
                $user_buy = Db::name('user')->where('id',$tradebuy->user_id)->find();
                if ($user_buy->mobile) {
                    Smslib::notice($user_buy->mobile,$msg);
                }

                // Smslib::smsNotice();
                $surplus -= $tradenum;
            }else{
                Cache::rm('running1'); 
                $this->error('没有买入订单code1');
            }
        }
        Cache::rm('running1'); 
        $this->success('完成订单匹配',['trade'=>$trade]);

        
    }

    //场外交易
    public function match2()
    {
        $this->error('stop');
        if (Cache::get('running2')) {
            $this->error('正在进行中');
        }
        Cache::set('running2',true);
        $tradeModel =new TradeModel();
        $trade =  $tradeModel->where('symbol','USD')->where('tosymbol','USDT')->where('surplusnum','>',0)->where('action','sell')->where('status','in',['0','1'])->find();
        if (!$trade) {
            Cache::rm('running2'); 
            $this->error('没有卖出订单');
        }
        $surplus = $trade->surplusnum;
        while ($surplus > 0) {
            $tradebuy =  $tradeModel->where('symbol','USD')->where('tosymbol','USDT')->where('action','buy')->where('surplusnum','>',0)->where('status','in',['0','1'])->where('user_id','<>',$trade->user_id)->find();
            // echo $tradeModel->getLastSql();
            if ($tradebuy) {
                $tradenum =  $surplus - $tradebuy->surplusnum > 0 ? $tradebuy->surplusnum : $surplus;

                Tradelog::Log(Random::tradeno(),$tradebuy->user_id,$tradebuy->user->username,$tradebuy->id,$trade->user_id,$trade->user->username,$trade->id,$tradenum,$tradenum,$trade->exch_rate,'waitting','admin',$trade['symbol'],$trade['tosymbol'],$trade['pay']);
                $tradeModel->dec('surplusnum',$tradenum)->where('id',$trade->id)->update(['status'=>'1']);
                $tradeModel->dec('surplusnum',$tradenum)->where('id',$tradebuy->id)->update(['status'=>'1']);


                $msg = "您订单号为{$tradeno}，买入USD{$tradenum}个，订单已经匹配成功，请及时登录后台，查找卖方信息并及时转账。如您30分钟内没有转账系统将取消这笔订单。恶意操作，可能造成封号。";
                $user_buy = Db::name('user')->where('id',$tradebuy->user_id)->find();
                if ($user_buy->mobile) {
                    Smslib::notice($user_buy->mobile,$msg);
                }

                $surplus -= $tradenum;
            }else{
                Cache::rm('running2'); 
                $this->error('没有买入订单code2');
            }
        }
        Cache::rm('running2'); 
        $this->success('完成订单匹配',['trade'=>$trade]);

    }

    public function sysinfo()
    {
        $member_login = config('site.member_login');
        $member_login_info = config('site.member_login_info');

        $this->success('返回成功',['member_login'=>$member_login,'info'=>$member_login_info]);
    }

    public function getinform()
    {
        $informlist = \app\common\model\Inform::page(input('page'))->limit(15)->select();
        $this->success('获取成功',['list'=>$informlist]);
    }

    public function inform()
    {
        $id = input('id');
        $inform = \app\common\model\Inform::get($id);
        $this->success('获取成功',['info'=>$inform]);
    }

    public function about()
    {
        $about_intro = config('site.about_intro');
        $about_rule = config('site.about_rule');
        $about_anwser = config('site.about_anwser');

        $this->success('获取成功',['about_intro'=>$about_intro,'about_rule'=>$about_rule,'about_anwser'=>$about_anwser]);
    }

}
